package cn.icatw.gulimall.member.service.impl;

import cn.icatw.common.utils.HttpUtils;
import cn.icatw.common.utils.PageUtils;
import cn.icatw.common.utils.Query;
import cn.icatw.gulimall.member.dao.MemberDao;
import cn.icatw.gulimall.member.dao.MemberLevelDao;
import cn.icatw.gulimall.member.entity.MemberEntity;
import cn.icatw.gulimall.member.entity.MemberLevelEntity;
import cn.icatw.gulimall.member.exception.PhoneExistException;
import cn.icatw.gulimall.member.exception.UsernameExistException;
import cn.icatw.gulimall.member.service.MemberService;
import cn.icatw.gulimall.member.vo.MemberLoginVo;
import cn.icatw.gulimall.member.vo.MemberRegisterVo;
import cn.icatw.gulimall.member.vo.SocialUser;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberRegisterVo vo) {
        MemberEntity memberEntity = new MemberEntity();
        //设置默认数据
        //默认等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(levelEntity.getId());
        //检查用户名和手机号唯一性。为了让controller能感知异常，采用异常机制
        checkPhoneUnique(vo.getPhone());
        checkUsernameUnique(vo.getUserName());

        memberEntity.setMobile(vo.getPhone());
        memberEntity.setUsername(vo.getUserName());
        //密码要进行加密存储。
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);
        memberEntity.setNickname(vo.getUserName());
        //TODO 其他的默认信息
        //保存
        baseMapper.insert(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        Long mobile = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException {
        Long userName = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (userName > 0) {
            throw new UsernameExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();
        //1、去数据库查询
        QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("username", loginacct).or().eq("mobile", loginacct);
        MemberEntity entity = this.baseMapper.selectOne(wrapper);
        if (entity == null) {
            //登陆失败
            return null;
        } else {
            //数据库查询到的密码
            String dbPassword = entity.getPassword();
            //利用BCryptPasswordEncoder将数据库查询的密码与用户输入的密码进行比对
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            //passwordEncoder.matches(password, dbPassword); 判断用户密码与数据库密码是否一致
            boolean matches = passwordEncoder.matches(password, dbPassword);
            if (matches) {
                return entity;
            } else {
                return null;
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        //登陆和注册合并逻辑
        String uid = socialUser.getUid();
        //1、判断当前社交用户是否已经登陆过系统
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity != null) {
            //   说明这个用户已经注册
            //更新用户的访问令牌的时间和access_token
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpiresIn(socialUser.getExpires_in());

            baseMapper.updateById(update);
            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in());
            return memberEntity;
        } else {
            //注册
            MemberEntity register = new MemberEntity();
            try {
                //查询当前社交用户的社交账号信息
                HashMap<String, String> query = new HashMap<>();
                query.put("access_token", socialUser.getAccess_token());
                query.put("uid", socialUser.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<>(), query);
                if (response.getStatusLine().getStatusCode() == 200) {
                    //查询成功
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    String profileImageUrl = jsonObject.getString("profile_image_url");

                    register.setNickname(name);
                    register.setGender("m".equals(gender) ? 1 : 0);
                    register.setHeader(profileImageUrl);
                    register.setCreateTime(new Date());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            //查询当前社交用户的社交账号信息
            register.setSocialUid(socialUser.getUid());
            register.setAccessToken(socialUser.getAccess_token());
            register.setExpiresIn(socialUser.getExpires_in());

            //把用户信息插入到数据库中
            this.baseMapper.insert(register);
            return register;
        }
    }
}

